//
//  EFDynamicSegmentView.m
//  ESPChatComps
//
//  Created by Sunjimin on 16/12/13.
//  Copyright © 2016年 Pansoft. All rights reserved.
//

#import "EFDynamicSegmentView.h"
#import "EFMessageService.h"
#import "EnvironmentVariable.h"
#import "Constant.h"
#import "EFChatListModel.h"
#import "Masonry.h"
#import "IBadgeView.h"
#import "ThemeKit.h"
#import "EFSegmentItem.h"

#define kDefaultTintColor   RGB(190, 116, 255)
#define kLeftMargin         15
#define kItemHeight         30
#define kBorderLineWidth    1.5
#define kBaseTag            1000

@interface EFDynamicSegmentView ()<JFMessageManagerDelegate,EFSegmentItemDelegate>

@property (nonatomic, strong) UIView                             *bgView;
@property (nonatomic, strong) NSMutableArray<EFSegmentItem *>    *itemsArray;
@property (nonatomic, strong) NSMutableArray                     *linesArray;
@property (nonatomic, strong) JFMessageManager                   *messageManager;

@end

@implementation EFDynamicSegmentView

- (id)initWithFrame:(CGRect)frame stubObjectArr:(NSArray *)stubObjectArr isBorderExist:(BOOL)isBorderExist norColor:(UIColor *)norColor selColor:(UIColor *)selColor{
    self = [super initWithFrame:frame];
    if (self) {
        [self addNoti];
        self.backgroundColor  = [UIColor clearColor];
        float viewWidth       = CGRectGetWidth(frame);
        float viewHeight      = CGRectGetHeight(frame);
        float init_x          = CGRectGetMinX(frame);
        float init_y          = CGRectGetMinY(frame);
        self.bgView = [[UIView alloc] initWithFrame:CGRectMake(kLeftMargin,
                                                               (viewHeight - kItemHeight)/2,
                                                               viewWidth -2*kLeftMargin,
                                                               kItemHeight)];
        self.bgView.backgroundColor    = [UIColor whiteColor];
        self.bgView.clipsToBounds      = YES;
        if (isBorderExist) {
            self.bgView.layer.cornerRadius = 5;
            self.bgView.layer.borderWidth  = kBorderLineWidth;
        }
        self.bgView.layer.borderColor  = [UIColor whiteColor].CGColor;
        [self addSubview:self.bgView];
        
        init_x = 0;
        init_y = 0;
        float itemWidth = CGRectGetWidth(self.bgView.frame)/stubObjectArr.count;
        float itemHeight = CGRectGetHeight(self.bgView.frame);
        if (stubObjectArr.count >= 1) {
            for (NSInteger i = 0; i < stubObjectArr.count; i++) {
                EFSegmentItem *item = [[EFSegmentItem alloc] initWithFrame:CGRectMake(init_x, init_y, itemWidth, itemHeight)
                                                                     index:i
                                                                       stu:stubObjectArr[i]
                                                                  norColor:(norColor == nil)?[UIColor redColor]:norColor
                                                                  selColor:(selColor == nil)?[UIColor whiteColor]:selColor
                                                                isSelected:(i == 0)? YES: NO
                                       ];
                init_x += itemWidth;
                item.tag = kBaseTag + i;
                [self.bgView addSubview:item];
                item.delegate = self;
                if (!self.itemsArray) {
                    self.itemsArray = [[NSMutableArray alloc] initWithCapacity:stubObjectArr.count];
                }
                [self.itemsArray addObject:item];
            }
            init_x = 0;
            for (NSInteger i = 0; i < stubObjectArr.count - 1; i++) {
                init_x += itemWidth;
                UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(init_x, 0, kBorderLineWidth, itemHeight)];
                lineView.backgroundColor = [UIColor whiteColor];
                [self.bgView addSubview:lineView];
                //save all lines
                if (!self.linesArray) {
                    self.linesArray = [[NSMutableArray alloc] initWithCapacity:stubObjectArr.count];
                }
                [self.linesArray addObject:lineView];
            }
        } else {
            NSException *exc = [[NSException alloc] initWithName:@"items count error"
                                                          reason:@"items count at least 1"
                                                        userInfo:nil];
            @throw exc;
        }
    }
    return self;
}

-(void)addNoti {
    //点击进入聊天列表之后二级菜单的同步
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(unreadcountRefresh:)
                                                 name:unreadcountChange
                                               object:nil];
    
    //收到消息之后的监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(unreadcountRefresh:)
                                                 name:@"chatCountChange"
                                               object:nil];
    //任务列表数据改变之后的二级菜单的同步
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(taskUnreadRefresh:)
                                                 name:@"taskUnreadcountChange"
                                               object:nil];
}

-(void)changeSegmentTitle:(NSString *)title index:(NSInteger)index {
    if(_itemsArray.count < index)  return;
    EFSegmentItem *item = [_itemsArray objectAtIndex:index];
    item.titleLabel.text =title;
}

//是否应用号消息
- (BOOL)isApplyAction:(NSString *)userIdStr{
    if ([[EFMessageService sharedMessageService].menuMap objectForKey:userIdStr]) {
        return YES;
    }
    return NO;
}

-(void)unreadcountRefresh:(NSNotification *)note {
    NSMutableArray *chatListArray = [[NSMutableArray alloc]init];
    chatListArray  = [EFMessageService sharedMessageService].listArray;
    NSInteger badgeValue = 0;
    for (EFChatListModel *model in chatListArray) {
        if (!model.isBother) {
            BOOL isApply = [self isApplyAction:[NSString stringWithFormat:@"%d",model.message.fromUserID]];
            if (!isApply) {
                badgeValue = badgeValue + [[JFMessageManager sharedMessageManager] unreadCountWithUserID:model.userId postType:[model.type integerValue]];
                [model.badgerNum integerValue];
            }
        }
    }
    [EnvironmentVariable setProperty:[NSString stringWithFormat:@"%ld",badgeValue] forKey:@"EFChatListViewController"];
    
    for (EFSegmentItem *item in _itemsArray) {
        NSString *showName = [item.stubObject getStringForKey:@"show" withDefaultValue:nil];
        if ([showName isEqualToString:note.object]) {
            if ([[EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"] integerValue]>99) {
                item.badgeView.badgeValue = @"99+";
            }else {
                item.badgeView.badgeValue = [EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"];
            }
        }
    }
}

-(void)taskUnreadRefresh:(NSNotification *)note {
    for (EFSegmentItem *item in _itemsArray) {
        NSString *showName = [item.stubObject getStringForKey:@"show" withDefaultValue:nil];
        if ([showName isEqualToString:note.object]) {
            if ([[EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"] integerValue]>99) {
                item.badgeView.badgeValue = @"99+";
            }else {
                item.badgeView.badgeValue = [EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"];
            }
            
        }
    }
}

- (void)selectItemAtIndex:(int)index {
    if (self.itemsArray.count < 1) {
        return;
    }
    for (int i = 0; i < self.itemsArray.count; i ++) {
        EFSegmentItem *item = self.itemsArray[i];
        if (i == index) {
            item.isSelected = YES;
        } else {
            item.isSelected = NO;
        }
        
    }
}
- (void)setTinColor:(UIColor *)tinColor{
    if (self.itemsArray.count < 1) {
        return;
    }
    if (_tinColor != tinColor) {
        self.bgView.layer.borderColor = tinColor.CGColor;
        for (NSInteger i = 0; i < self.itemsArray.count; i ++) {
            EFSegmentItem *item = self.itemsArray[i];
            item.selColor = tinColor;
            [item setNeedsDisplay];
        }
        for (NSInteger i = 0; i < self.linesArray.count; i ++) {
            UIView *lineView = self.linesArray[i];
            lineView.backgroundColor = tinColor;
        }
    }
}

- (void)ItemStateChanged: (EFSegmentItem *)currentItem index:(NSInteger)index isSelected:(BOOL)isSelected stubObject:(StubObject *)stubObject {
    if (self.itemsArray.count < 1) {
        return;
    }
    for (int i = 0; i < self.itemsArray.count; i ++) {
        EFSegmentItem *item = self.itemsArray[i];
        item.isSelected = NO;
    }
    currentItem.isSelected = YES;
    if (_delegate && [_delegate respondsToSelector:@selector(segmentView:selectedIndex:stubObject:)]) {
        [_delegate segmentView:self selectedIndex:index stubObject:stubObject];
    }
}

-(void)segmentMoreMenuDidSelectWithIndex:(NSInteger)index stubobject:(StubObject *)stubObject segmentFrame:(CGRect)segmentFrame {
    if (_delegate && [_delegate respondsToSelector:@selector(segmentViewMoreMenuDidSelectWithIndex:stubobject:segmentFrame:segmentViewFrame:)]) {
        [_delegate segmentViewMoreMenuDidSelectWithIndex:index stubobject:stubObject segmentFrame:segmentFrame segmentViewFrame:self.frame];
    }
}

@end
